const jwt = require('jsonwebtoken');
const {validate} = require("./validator");
const {BadRequest} = require("./utils/api_error");

const JWT_SECRET = 'nlISVY4qvgA3eHVlPTrxUolZP3Cku842';


const ApiError = require("./utils/api_error");

function errorHandler(err, req, res, next) {
    // 如果 headers 已经发送，交给默认处理器
    if (res.headersSent) return next(err);

    if (err instanceof ApiError) {
        return res.status(err.status).json({
            success: false,
            message: err.message,
            code: err.code || undefined,
        });
    }

    // Sequelize / Validation 错误常见处理（示例）
    if (err.name === 'SequelizeValidationError' || err.name === 'ValidationError') {
        const msg = Array.isArray(err.errors) ? err.errors.map(e => e.message).join('; ') : err.message;
        return res.status(400).json({ success: false, message: msg });
    }

    const status = err.status || 500;
    const message = err.message || 'Internal Server Error';
    return res.status(status).json({ success: false, message });
}

function asyncHandler(fn) {
    return (req, res, next) => {
        Promise.resolve(fn(req, res, next)).catch(next);
    };
}

function authMiddleware(req, res, next) {
    const auth = req.headers.authorization;
    if (!auth) return res.status(401).json({ error: '缺少授权' });
    const token = auth.split(' ')[1];
    try {
        req.loginUser = jwt.verify(token, JWT_SECRET);
        next();
    } catch (e) {
        return res.status(401).json({ error: '无效或过期的 token' });
    }
}

function responseMiddleware(req, res, next) {
    res.success = (data = null, message = '') => {
        return res.json({
            success: true,
            message,
            data,
        });
    };

    res.fail = (message = 'error', status = 400, extra = null) => {
        const payload = {
            success: false,
            message,
        };
        if (extra !== null) payload.data = extra;
        return res.status(status).json(payload);
    };

    next();
}

/**
 * validateRequest(schema)
 * schema 按 utils/validator.js 的格式
 *
 * 用法：
 * router.post('/register', validateRequest(registerSchema), asyncHandler(...))
 */
function validateRequest(schema = {}) {
    return (req, res, next) => {
        const toValidate = {
            body: req.body,
            query: req.query,
            params: req.params,
        };

        const { value, errors } = validate(schema, toValidate);

        if (errors.length) {
            // 抛出 ApiError，由全局 errorHandler 统一处理
            throw BadRequest(errors.join('; '));
        }

        // 将校验并类型转换后的值写回 req（只写被 schema 指定的部分）
        if (value.body) req.body = Object.assign({}, req.body, value.body);
        if (value.query) req.query = Object.assign({}, req.query, value.query);
        if (value.params) req.params = Object.assign({}, req.params, value.params);

        next();
    };
}



module.exports = {
    JWT_SECRET,
    authMiddleware,
    responseMiddleware,
    validateRequest,
    errorHandler,
    asyncHandler
}